# -*- coding: UTF-8 -*-

import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from app.monitor_metrics.models.prom_alarm_template import PromAlarmTemplate
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger


__all__ = ['PromHostInfo']

class PromHostInfo(Base, SessionMixin):
    '''
    主机信息
    '''
    __tablename__ = "prom_host_info"
    name = Column(String(128), nullable=False, index=True, comment='主机名')
    # http or https
    scheme = Column(String(8), nullable=False, comment='协议')
    ip = Column(String(24), nullable=False, index=True,comment='ip地址')
    port = Column(Integer, nullable=False, index=True,comment='端口')
    metrics = Column(String(24), nullable=False, comment='指标路径')
    labels = Column(JSON, nullable=False, default={}, comment='自定义标签')
    # true/false
    state = Column(Boolean, default=text('true'), nullable=False, comment='状态')
    # 主机自定义的告警策略，只影响到本机
    template_uuid = Column(Integer, nullable=True, comment='主机自定义的告警模板')
    comment = Column(String(256), nullable=True, comment='主机说明')

    host_group_uuid = Column(Integer, ForeignKey('prom_host_group.uuid'), comment='所属主机组uuid')

    __table_args__ = (
        Index('idx_prom_host_info_name', 'name', unique=True),
        Index('idx_targets_host_info_ip_port', 'ip', 'port', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<name='{self.name}'=> {self.scheme}://{self.ip}:{self.port}{self.path}'>"



    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        result["host_group"] = self.prom_host_group.name
        result["template_name"] = PromAlarmTemplate.get_object_by_uuid(db, result["template_uuid"]).name
        return result


    @classmethod
    def get_object_info_by_group_uuid(cls, db: Session, host_group_uuid: int):
        host_infos = db.query(cls).filter(
            cls.host_group_uuid == host_group_uuid
        ).order_by(cls.name.asc()).all()

        result = [
            cls.get_object_info_by_uuid(db, item.uuid)
            for item in host_infos
        ]

        return result


    @classmethod
    def get_all_host_info(cls, db: Session):
        host_infos = db.query(cls).to_dict()
        return host_infos